﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using Tesla.Validador;

namespace Rendiciones.Logica.Modelos.Validaciones
{
    internal class RequiereMailValido : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
                return new UsefullValidationResult(new[] { validationContext.MemberName }, EValidationResolution.Success);

            if (value is string)
            {
                var mail = (string)value;
                if (!string.IsNullOrEmpty(mail) && !Regex.IsMatch(mail, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
                    return new UsefullValidationResult(new[] { validationContext.MemberName }, EValidationResolution.Error,
                        ErrorMessage);
                return new UsefullValidationResult(new[] { validationContext.MemberName }, EValidationResolution.Success);
            }
            else
                throw new ValidationException("La validación no es compatible con el valor que esta utilizando");
        }
    }
}